<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let arrData = [
            { key: 1, title: '1', parent: 0, isLeaf: false, children: [] },
            { key: 11, title: '1-1', parent: 1, isLeaf: false, children: [] },
            { key: 111, title: '1-1-1', parent: 11, isLeaf: true, children: [] },
            { key: 112, title: '1-1-2', parent: 11, isLeaf: false, children: [] },
            { key: 1121, title: '1-1-2-1', parent: 112, isLeaf: true, children: [] },
            { key: 12, title: '1-2', parent: 1, isLeaf: false, children: [] },

            { key: 2, title: '2', parent: 0, isLeaf: false, children: [] },
            { key: 21, title: '2-1', parent: 2, isLeaf: true, children: [] },
            { key: 22, title: '2-2', parent: 2, isLeaf: false, children: [] },
            { key: 221, title: '2-2-1', parent: 22, isLeaf: true, children: [] },

            { key: 3, title: '3', parent: 0, isLeaf: false, children: [] },
            { key: 31, title: '3-1', parent: 3, isLeaf: true, children: [] },
            { key: 32, title: '3-2', parent: 3, isLeaf: true, children: [] }
        ]

        // function toTree(arr, parentId) {
        //     parentId = !parentId ? 0 : parentId
        //     const parent = arr.find((item)=> item.key === parentId)
        //     const children = parent ? parent.children : []
        //     const rootNode = arr.filter((item)=> item.parent === parentId)
        //     rootNode.forEach((item)=> {
        //         if(item.isLeaf) return
        //         toTree(arr, item.key)
        //     })
            
        //     children.push(...rootNode)
        //     return children
        // }
        // console.log(toTree(arrData))

        function toTree2(arr, pId) {
            pId = pId ? pId : 0
            const parent = arr.find((item)=> item.key === pId)
            const children = parent ? parent.children : []
            const nodes = arr.filter((item)=> item.parent === pId)
            nodes.forEach((item)=> {
                children.push(item)
                toTree2(arr, item.key)
            })
            return children
        }
        console.log(toTree2(arrData))
    </script>
</body>
</html>